package com.dpad.telematicsclientapp.utils;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;


import com.dpad.telematicsclientapp.android.R;
import com.dpad.telematicsclientapp.library.util.RxSchedulerUtils;
import com.dpad.telematicsclientapp.mvp.kit.Kits;
import com.dpad.telematicsclientapp.netlibrary.MainApplicaton;
import com.dpad.telematicsclientapp.netlibrary.base.basecopy.AppManager;
import com.dpad.telematicsclientapp.netlibrary.base.basecopy.BaseCopyActivity;
import com.dpad.telematicsclientapp.netlibrary.entity.CuscResult;
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.CheckUpdateAppVO;
import com.dpad.telematicsclientapp.netlibrary.newapp.repository.UpdateAppepository;
import com.dpad.telematicsclientapp.util.service.DownloadService;
import com.dpad.telematicsclientapp.util.utils.DialogUtil;
import com.dpad.telematicsclientapp.util.utils.T;
import com.dpad.telematicsclientapp.util.utils.UIUtils;
import com.socks.library.KLog;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.SortedMap;
import java.util.TreeMap;


import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * @创建者 booobdai.
 * @创建时间 2017/9/5  17:00.
 * @描述 ${App}.
 */
public class AppUpdateUtil {

    private static final String TAG = AppUpdateUtil.class.getSimpleName();

    //APP类型, android-2
    private static final int APP_TYPE = 2;

    private static boolean forceUpdate = false;
    private static Intent intent;
//    private static Activity mActivity;

    /**
     * 检查应用版本 更新
     *
     * @param activity
     * @param showLoadding 是否显示进度圈(用户主动点击检查版本)
     */
    public static void checkVersion(final AppCompatActivity activity, final boolean showLoadding, final boolean showToast) {
        BaseCopyActivity baseCopyActivity = null;
        if (activity instanceof BaseCopyActivity) {
            baseCopyActivity = (BaseCopyActivity) activity;
        }
        if (showLoadding) {
            if (baseCopyActivity != null) {
                baseCopyActivity.loading("");
            }
        }
        CompositeSubscription subscriptions = new CompositeSubscription();
        SortedMap<String, String> paramsMap = new TreeMap<String, String>();
//        paramsMap.put("phone", phone);
        BaseCopyActivity finalBaseCopyActivity = baseCopyActivity;
        Subscription subscription = UpdateAppepository.getInstance().TService(paramsMap).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).compose(RxSchedulerUtils.normalSchedulersTransformer()).subscribe(new Observer<CuscResult<CheckUpdateAppVO>>() {
                    @Override
                    public void onCompleted() {
                        if (finalBaseCopyActivity != null) {
                            finalBaseCopyActivity.loadingComplete();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
//                        T.showToastSafe("网络异常");
                        KLog.e(e.toString());
                        if (finalBaseCopyActivity != null) {
                            finalBaseCopyActivity.loadingComplete();
                        }
                    }

                    @Override
                    public void onNext(CuscResult<CheckUpdateAppVO> stringCuscResult) {
                        if (stringCuscResult.getCode().equals("00000")) {
                            if (Kits.Empty.check(stringCuscResult.getResult())) {
                                if (finalBaseCopyActivity != null && showLoadding&&showToast) {
                                    T.showToastSafe(R.string.toast_already_new_version);
                                }
                                return;
                            }
                            if (Kits.Empty.check(stringCuscResult.getResult().getUrl())) {
                                if (finalBaseCopyActivity != null && showLoadding&&showToast) {
                                    T.showToastSafe(R.string.toast_already_new_version);
                                }
                                return;
                            }
                            showNewVersion(activity, showLoadding, stringCuscResult.getResult());
                        } else {
                            if (showLoadding) {
                                T.showToastSafe(stringCuscResult.getMessage());
                            }
                        }

                    }
                });
        subscriptions.add(subscription);
    }

    /**
     * 提示新版本
     *
     * @param activity
     * @param showLoadding 是否显示进度圈(用户主动点击检查版本)
     * @param data
     */
    private static void showNewVersion(final AppCompatActivity activity, boolean showLoadding, CheckUpdateAppVO data) {
        //是否强制更新
        forceUpdate = data.getForceFlag();
        final String downUrl = data.getUrl();
        String releaseNote = data.getVersDes();
        String verName = data.getVersCode();
        String content;
        String cancleText;
        String confirmText;
        String title = UIUtils.getString(R.string.dialog_new_version);
        final String fileName = Kits.Package.getAppName(activity) + "_" + verName + ".apk";
        if (forceUpdate) {
//            content = "重要版本更新\n版本号: " + verName + "\n更新说明:\n" + releaseNote + ",请更新后使用.";
            content = "更稳定、快速、多彩的功能和体验，立即点击升级！";
            cancleText = "退出";
            confirmText = "更新";
        } else {
            content = "更稳定、快速、多彩的功能和体验，立即点击升级！";
            cancleText = UIUtils.getString(R.string.dialog_cancel);
            confirmText = "更新";
        }
//        long lastCheckVersionTime = (long) SPUtil.get(activity, SPConfig.APP_CHECK_NEW_VERSION_DATE, 0L);
        long currentTimeMillis = System.currentTimeMillis();
//        boolean isThreeDayAgo = (currentTimeMillis - lastCheckVersionTime) > 1000 * 60 * 60 * 24 * 3;
        KLog.d(TAG, "是否用户主动检查更新: " + showLoadding + ", 是否强制更新: " + forceUpdate);
        //如果是用户主动点击检查更新 或 强制更新 或 最后一次提醒是三天前,则提醒更新; 否则不提醒
        if (showLoadding) {
//            SPUtil.put(activity, SPConfig.APP_CHECK_NEW_VERSION_DATE, currentTimeMillis);
            Dialog dialog = DialogUtil.showBasicDialog(true, activity, title, content, cancleText, confirmText,
                    (dialog1, confirm) -> {
                        if (confirm) {
                            dialog1.dismiss();
                            checkPermission(activity, downUrl, fileName);

                        } else if (forceUpdate) {
                            AppManager.getInstance().exitApp(MainApplicaton.getContext());
                            //退出应用
//                            MainApplicaton.getInstance().removeAllActivities();
                        }
                    });
            //强制更新dialog不能返回关闭
            dialog.setCancelable(!forceUpdate);
        }
    }

    /**
     * 检查文件读写权限
     *
     * @param activity
     * @param downLoadUrl 下载地址
     * @param fileName    下载文件名
     */
    private static void checkPermission(final Activity activity, final String downLoadUrl, final String fileName) {
        RxPermissions rxPermissions = new RxPermissions(activity);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        downloadAppByService(activity, downLoadUrl, fileName, forceUpdate);
                    } else {
                        String title = UIUtils.getString(R.string.dialog_warning_title);
                        String content = UIUtils.getString(R.string.permission_storage_error);
                        DialogUtil.showPermissionSettingDialog(activity, title, content, true);
                    }
                });
    }

    /**
     * 开启下载服务下载App
     *
     * @param activity
     * @param downLoadUrl
     * @param fileName
     */
    private static void downloadAppByService(final Activity activity, String downLoadUrl, String fileName, boolean forceUpdate) {
//        mActivity = activity;
        intent = new Intent(activity, DownloadService.class);
        intent.putExtra(DownloadService.INTENT_DOWNLOAD_URL, downLoadUrl);
        intent.putExtra(DownloadService.INTENT_DOWNLOAD_FILE_NAME, fileName);
        intent.putExtra(DownloadService.INTENT_DOWNLOAD_FORCEUPDATE, forceUpdate);
        activity.startService(intent);
    }

//    public static void stopDownService() {
//        if (mActivity != null) {
//            mActivity.stopService(intent);
//        }
//    }

}
